<template>
  <div class="wrapper">
    <FormPanel ref="formPanel" :list="inputs" :cols="2" labelWidth="150" :formType="type" :isSubmitBtn="false" @formChange="formChangeHandle" />
    <!-- 经销商table -->
    <!-- <FilterTable
      ref="table"
      :columns="columns"
      :isSelectColumn="isSelectColumn"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :onColumnsChange="columns => this.columns = columns"
    ></FilterTable>-->
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDialog">关 闭</el-button>
      <!-- <el-button
        v-if="this.type == 'show' && this.materialStatus == '25361003'"
        type="primary"
        @click="tyDialog"
      >停 用</el-button>-->
    </div>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import {
  getmaterialTypeOneList,
  saveMaterials,
  updateMaterial,
  updateDealerMaterial,
  selectDealerMaterialById,
  saveDealerMaterial,
  selectMaterialListByBill
} from '@/api/cms-api/projectOperating/program/push';
export default {
  mixins: [dictionary],
  components: {},
  props: {
    type: {
      type: String,
      required: true
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  mounted() {
    // console.log(this.value);
  },
  data() {
    return {
      inputs: this.getInputs(),
      inputsData: {},
      formValue: {},
      dataParams: {}, //父类参数
      caseUrlList: [],
      columns: this.creatHeader(),
      isSelectColumn: false,
      fetchApi: getProjectMaterialDealer, //ipa 接口获取营销素材对应经销商信息
      fetchParams: { materialId: this.rowData.materialId }, //参数
      orgUrls: []
    };
  },
  created() {
    this.init();
  },
  methods: {
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '经销商代码',
          dataIndex: 'ownerCode',
          sorter: true
        },
        {
          title: '经销商简称',
          dataIndex: 'dealerName',
          sorter: true
        },
        {
          title: '是否查看',
          dataIndex: 'isView',
          sorter: true,
          filterItems: this.createDictList('1004'),
          render: props => {
            //编码转汉字
            return <span>{this.createDictText(props.row.isView, '1004')}</span>;
          }
        },
        {
          title: '首次查看人',
          dataIndex: 'firstViewPerson',
          sorter: true
        },
        {
          title: '首次查看时间',
          dataIndex: 'firstViewTime',
          sorter: true,
          render: props => {
            return <span>{this.formatDates(props.row.firstViewTime)} </span>;
          }
        }
      ];
    },
    formatDates: function(value) {
      // 这里的 value 就是需要过滤的数据
      if (value == null || value == '') {
        return '';
      }
      var date = new Date(value);
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      return year + '-' + month + '-' + day;
    },
    async init() {
      if (this.type === 'show') {
        // console.log(this.rowData);
        if (this.rowData.id == null) {
          //全网下发
          //判断是否需要反馈
          if (this.rowData.isNeedFeedback == 10041002) {
            //否
            await saveDealerMaterial(this.rowData);
          } else {
            //反馈状态
            this.rowData = Object.assign(this.rowData, { feedbackStatus: 25271001 });
            await saveDealerMaterial(this.rowData);
          }
        } else {
          //不是全网下发，下发到某个经销商，事先表里已有数据，直接修改首次查看人字段
          //如果id不为null，根据id查询是否被查看，如果被查看则走原始update,否则走自定义的update
          let res = await selectDealerMaterialById(this.rowData.id);
          if (res.resultCode === 200) {
            if (this.rowData.isNeedFeedback == 10041002) {
              //是否首次被查看
              if (res.data.isView == null) {
                //是首次查看
                await updateDealerMaterial(this.rowData, this.rowData.id);
              }
            } else {
              if (res.data.isView == null) {
                //反馈状态
                this.rowData = Object.assign(this.rowData, { feedbackStatus: 25271001 });
                //是首次查看
                await updateDealerMaterial(this.rowData, this.rowData.id);
              }
            }
          }
        }
        this.materialId = this.rowData.materialId;
        // console.log(this.materialId);
        this.materialStatus = this.rowData.materialStatus;
        //初始化二级
        this.initmaterialTypeTwo(this.rowData.materialTypeOne);
        //初始化三级
        this.initmaterialTypeThree(this.rowData.materialTypeTwo);
        //初始化四级
        this.initmaterialTypeFour(this.rowData.materialTypeThree);
        //初始化五级
        this.initmaterialTypeFive(this.rowData.materialTypeFour);
        //大附件
        let res = {};
        let fileParams = { materialId: this.materialId, billType: 25721003 };
        res = await selectMaterialListByBill(fileParams);
        if (res.data.length > 0) {
          for (let j = 0; j < res.data.length; j++) {
            this.orgUrls.push(res.data[j].fileId);
          }
        }
        this.inputs.forEach(x => {
          x.initialValue = this.rowData[x.fieldName];
          if (x.fieldName == 'originalFileUrl') {
            x.initialValue = this.orgUrls;
          }
        });
      }
    },
    formChangeHandle(val) {
      this.formValue = val;
    },
    getInputs() {
      return [
        {
          type: 'INPUT',
          label: '营销素材代码',
          disabled: true,
          fieldName: 'materialCode',
          placeholder: '系统自动生成',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '营销素材名称',
          fieldName: 'materialName',
          placeholder: '',
          initialValue: ''
          // rules: [{ required: true, message: '请输入营销素材名称', trigger: 'blur' }, { min: 3, max: 5, message: '长度在 ？ 到 ？ 个字符', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '来源部门',
          disabled: true,
          fieldName: 'orgName',
          placeholder: '系统自带',
          initialValue: ''
        },
        {
          type: 'SELECT',
          label: '营销素材类型-一级',
          fieldName: 'materialTypeOne',
          placeholder: '',
          //           request:{
          //                   fetchApi:getmaterialTypeOneList,
          //                   params:{},
          //                   valueKey:'materialTypeId',
          //                   textKey:'materialTypeName'},
          itemList: [],
          change: value => {
            this.initmaterialTypeTwo(value);
          }
          // rules: [{ required: true, message: '请选择营销素材类型-一级', trigger: 'blur' }]
        },
        {
          type: 'SELECT',
          label: '营销素材类型-二级',
          fieldName: 'materialTypeTwo',
          placeholder: '',
          itemList: [],
          change: value => {
            this.initmaterialTypeThree(value);
          }
          // rules: [{ required: true, message: '请选择营销素材类型-二级', trigger: 'blur' }]
        },
        {
          type: 'SELECT',
          label: '营销素材类型-三级',
          fieldName: 'materialTypeThree',
          placeholder: '',
          itemList: [],
          change: value => {
            this.initmaterialTypeFour(value);
          }
        },
        {
          type: 'SELECT',
          label: '营销素材类型-四级',
          fieldName: 'materialTypeFour',
          placeholder: '',
          itemList: [],
          change: value => {
            this.initmaterialTypeFive(value);
          }
        },
        {
          type: 'SELECT',
          label: '营销素材类型-五级',
          fieldName: 'materialTypeFive',
          placeholder: '',
          itemList: []
        },
        {
          type: 'INPUT',
          label: '使用场景',
          fieldName: 'usedScenes',
          placeholder: '',
          initialValue: '',
          placeholder: ''
        },
        // {
        //   type: 'SELECT',
        //   label: '营销素材状态',
        //   disabled: true,
        //   fieldName: 'materialStatus',
        //   placeholder: '请选择...',
        //   initialValue: '25361001',
        //   itemList: this.createDictList('2536')
        // },
        {
          type: 'SELECT',
          label: '是否需要反馈',
          fieldName: 'isNeedFeedback',
          placeholder: '',
          itemList: this.createDictList('1004')
          // rules: [{ required: true, message: '请选择是否需要反馈', trigger: 'blur' }]
        },
        {
          type: 'DATE',
          label: '反馈截止日期',
          fieldName: 'feedbackEndDate',
          valueFormat: 'yyyy-MM-dd',
          placeholder: '',
          itemList: []
          // rules: [{ required: true, message: '请输入反馈截止日期', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '审核人',
          fieldName: 'reviewPersonName',
          placeholder: '',
          initialValue: '',
          disabled: false,
          readonly: true
        },
        {
          type: 'INPUT',
          label: '审核意见',
          fieldName: 'reviewIdea',
          placeholder: '',
          initialValue: '',
          disabled: false,
          readonly: true
        },
        {
          type: 'TEXT_AREA',
          label: '原始文件下载地址',
          fieldName: 'originalFileUrl',
          placeholder: '',
          initialValue: '',
          selfCols: 2
        },
        {
          type: 'UPLOAD_FILE',
          label: '附件缩略图',
          fieldName: 'caseUrl',
          selfCols: 2,
          // rules: [{ limit: 1, validator: this.validateFn, message: '最多上传1张', trigger: 'change' }],
          upload: {
            actionUrl: '/api/file/oss/upload'
          }
        }
        // {
        //   type: 'SELECT',
        //   label: '是否全网下发',
        //   fieldName: 'isNetworkIssued',
        //   placeholder: '请选择...',
        //   itemList: this.createDictList('1004'),
        //   rules: [{ required: true, message: '请选择是否全网下发', trigger: 'blur' }]
        // }
      ];
    },
    //取营销素材类型-一级
    async initmaterialTypeOne() {
      let res = [];
      this.dataParams = { parentTypeId: '' };
      let rd = await getmaterialTypeOneList(this.dataParams);
      for (let i in rd.data) {
        res.push({ text: rd.data[i].materialTypeName, value: rd.data[i].materialTypeId });
      }
      this.inputs[3].itemList = res;
    },
    //取营销素材类型-二级
    async initmaterialTypeTwo(parentTypeId) {
      let res = [];
      this.dataParams = { parentTypeId: parentTypeId };
      let rd = await getmaterialTypeOneList(this.dataParams);
      for (let i in rd.data) {
        res.push({ text: rd.data[i].materialTypeName, value: rd.data[i].materialTypeId });
      }
      this.inputs[4].itemList = res;
    },
    //取营销素材类型-三级
    async initmaterialTypeThree(parentTypeId) {
      let res = [];
      this.dataParams = { parentTypeId: parentTypeId };
      let rd = await getmaterialTypeOneList(this.dataParams);
      for (let i in rd.data) {
        res.push({ text: rd.data[i].materialTypeName, value: rd.data[i].materialTypeId });
      }
      this.inputs[5].itemList = res;
    },
    //取营销素材类型-四级
    async initmaterialTypeFour(parentTypeId) {
      let res = [];
      this.dataParams = { parentTypeId: parentTypeId };
      let rd = await getmaterialTypeOneList(this.dataParams);
      for (let i in rd.data) {
        res.push({ text: rd.data[i].materialTypeName, value: rd.data[i].materialTypeId });
      }
      this.inputs[6].itemList = res;
    },
    //取营销素材类型-五级
    async initmaterialTypeFive(parentTypeId) {
      let res = [];
      this.dataParams = { parentTypeId: parentTypeId };
      let rd = await getmaterialTypeOneList(this.dataParams);
      for (let i in rd.data) {
        res.push({ text: rd.data[i].materialTypeName, value: rd.data[i].materialTypeId });
      }
      this.inputs[7].itemList = res;
    },
    checkedEnclosure() {
      //选择附件
    },
    changeHandle(data) {
      this.inputsData = data;
      this.$emit('close', data);
    },
    //停用
    async tyDialog() {
      this.$refs.formPanel.SUBMIT_FORM();
      if (this.formValue !== null) {
        //追加隐藏状态字段
        this.formValue = Object.assign({}, { materialStatus: 25361005 }, this.formValue);
        let result = {};
        if (this.type === 'show') {
          for (let i = 0; i < this.formValue.caseUrl.length; i++) {
            this.caseUrlList.push(Object.assign({}, { name: this.formValue.caseUrl[i].name }, { url: this.formValue.caseUrl[i].url }));
          }
          this.formValue = Object.assign({}, { fileUrl: this.caseUrlList }, this.formValue);
          result = await updateMaterial(this.formValue, this.materialId);
          if (result.resultCode === 200) {
            this.$notify.success({ title: '提示信息', message: '已停用!' });
            this.closeDialog('refresh');
          }
        }
      }
    },
    //取消操作
    closeDialog(param) {
      this.$emit('close', false, param);
    }
  },
  mounted() {
    //初始化营销素材类型-一级
    this.initmaterialTypeOne();
  }
};
</script>
<style scoped>
.wrapper {
  height: calc(100vh - 110px);
}
</style>
